package com.haiwen.com;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Create by song_dl
 * 2021/6/17
 *
 * 关于请求乱码的问题：
 * 在tomcat7及之前版本
 *    get 和 post 请求都会乱码
 *  在tomc7之后
 *    get请求不会乱码，post请求会乱码
 */

@WebServlet("/request03")
public class HttpServletRequest4 extends HttpServlet {
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        //设置编码格式 utf-8
        req.setCharacterEncoding("UTF-8");

        //1.接收请求的参数
        String userName = req.getParameter("userName");
        String userPwd = req.getParameter("userPwd");
        System.out.println(userName);
        System.out.println(userPwd);

        //userName=admin userPwd=123456 登录成功跳转欢迎admin界面 登录失败--提示用户名或者密码错误
        //1.判断用户名
        if(userName == null || !"admin".equals(userName)) {

                //设置request的请求域--相当于设置一个特殊的变量 把存入动态界面 作用域：把数据存储起来
                req.setAttribute("msg","用户名输入不正确");

                //请求转发
                req.getRequestDispatcher("login.jsp").forward(req,resp);
                return;
        }
        if (userPwd == null ||  !"123456".equals(userPwd)) {
                req.setAttribute("msg","用户密码输入不正确");

                //请求转发
                req.getRequestDispatcher("login.jsp").forward(req,resp);
                return;
        }

                //登录成功跳转到main.jsp
                req.setAttribute("userName",userName);//将用户名设置到作用域中
               //请求转发到main.jsp
                req.getRequestDispatcher("main.jsp").forward(req,resp);
        }
}